package com.common.server.modules.qrcode.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.zxing.Result;
import com.common.server.common.config.zxingcode.LogoConfig;
import com.common.server.common.exception.CustomerException;
import com.common.server.common.util.FileType;
import com.common.server.common.util.FileUtil;
import com.common.server.common.util.ZXingCodeUtil;
import com.common.server.modules.file.entity.FileEntity;
import com.common.server.modules.file.mapper.FileMapper;
import com.common.server.modules.qrcode.entity.ZXingCode;
import com.common.server.modules.qrcode.service.QRCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 描述：二维码服务实现
 * <p>
 * 作者：Ostrich Hu
 * 时间：2019/10/12 15:35 星期六
 */
@Service
public class QRCodeServiceImpl extends ServiceImpl<FileMapper, FileEntity> implements QRCodeService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${sys.config.uploadFilePath}")
    private String uploadPath;

    /**
     * ZXing解码
     *
     * @param qrFile
     * @return
     */
    @Override
    public String decode(File qrFile) {
        try {
            BufferedImage image = ImageIO.read(qrFile);
            if (image == null) {
                throw new CustomerException("the decode image may be not exit.");
            }
            Result result = ZXingCodeUtil.parseQR_CODEImage(image);
            FileUtil.deleteCycleFile(qrFile.getAbsolutePath());
            return result.getText();
        } catch (Exception e) {
            throw new CustomerException("解析二维码文件异常", e);
        }
    }

    @Override
    public void genZXingCode(ZXingCode zXingCode, HttpServletRequest request, HttpServletResponse response) {
        try {
            String realPath = uploadPath + zXingCode.getPutPath() + File.separator;
            File uploadDir = new File(realPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            String content = zXingCode.getContent();
            String imageName = String.format("%s_qr.png", content.contains("http://") ? content.substring(7) : content);
            File qrFile = new File(uploadDir, imageName);
            // 设置Logo图片
            if (zXingCode.isLogoFlg()) {
                String uri = "static" + File.separator + "images" + File.separator + "logo.png";
                ClassPathResource resource = new ClassPathResource(uri);
                File file = resource.getFile();
                zXingCode.setLogoPath(file.getAbsolutePath());
            }
            zXingCode.setHints(ZXingCodeUtil.getDecodeHintType());
            // Logo图片参数设置
            zXingCode.setLogoConfig(new LogoConfig());
            // 图片写出
            ImageIO.write(ZXingCodeUtil.getQR_CODEBufferedImage(zXingCode), "png", qrFile);
            //解决下载时中文名称乱码
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            String fileName = FileType.encodeFileName(request, qrFile.getName());
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            FileUtil.downloadFile(qrFile, response);
            //删除生成的临时二维码
            FileUtil.deleteCycleFile(realPath);
        } catch (Exception e) {
            throw new CustomerException("生成二维码异常", e);
        }
    }

    @Override
    public void genZXingSelfCode(MultipartFile file, ZXingCode zXingCode, HttpServletRequest request, HttpServletResponse response) {
        try {
            String realPath = uploadPath + zXingCode.getPutPath() + File.separator;
            String logoPath = realPath + "logo" + File.separator;
            //上传logo
            FileUtil.uploadFile(file, logoPath, file.getOriginalFilename());
            File uploadDir = new File(realPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            String imageName = String.format("%s_qr.png", zXingCode.getContent());
            File qrFile = new File(uploadDir, imageName);
            // Logo 图片参数设置
            zXingCode.setLogoFlg(true);
            zXingCode.setLogoPath(logoPath + file.getOriginalFilename());
            zXingCode.setLogoConfig(new LogoConfig());
            zXingCode.setHints(ZXingCodeUtil.getDecodeHintType());
            BufferedImage bim = ZXingCodeUtil.getQR_CODEBufferedImage(zXingCode);
            ImageIO.write(bim, "png", qrFile);    // 图片写出
            //解决下载时中文名称乱码
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            String fileName = FileType.encodeFileName(request, qrFile.getName());
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            FileUtil.downloadFile(qrFile, response);
            //删除临时的logo图片
            FileUtil.deleteCycleFile(logoPath);
        } catch (Exception e) {
            throw new CustomerException("生成二维码异常", e);
        }
    }
}
